package net.ariel.myideablog.impl;

import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import net.ariel.myideablog.dao.ILink;
import net.ariel.myideablog.model.Link;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class LinkImpl implements ILink {

	PersistenceManagerFactory persistenceManagerFactory;
	
	public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) {
		this.persistenceManagerFactory = pmf;
	}
	
	@Override
	public List<Link> getAllLinks() {
		// TODO Auto-generated method stub
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		String query = "select from "+Link.class.getName();
		return (List<Link>)pm.newQuery(query).execute();
	}

	@Override
	public List<Link> getLinksByPage(int offset, int limit) {
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		String query = "select from "+Link.class.getName()+" range "+Integer.toString(offset)+" , "+Integer.toString(limit);
		return (List<Link>)pm.newQuery(query).execute();
	}
	
	@Override
	public void saveLink(Link link) {
		// TODO Auto-generated method stub
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			pm.makePersistent(link);
		}
		finally {
			pm.close();
		}
	}
	
	@Override
	public Link getLink(String linkKey) {
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			return pm.getObjectById(Link.class, KeyFactory.stringToKey(linkKey));
		}
		finally {
			pm.close();
		}
	}
	
	@Override
	public void updateLink(String linkKey, Link newLink) {
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			Link link = pm.getObjectById(Link.class, KeyFactory.stringToKey(linkKey));
			link.setTitle(newLink.getTitle());
			link.setUrl(newLink.getUrl());
		}
		finally {
			pm.close();
		}
	}

	@Override
	public void deleteLink(String linkKey) {
		// TODO Auto-generated method stub
		Key key = KeyFactory.stringToKey(linkKey);
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			Link link = pm.getObjectById(Link.class, key);
			pm.deletePersistent(link);
		}
		finally {
			pm.close();
		}
	}

	@Override
	public int getLinkNumber() {
		String query = "select count(this) from "+Link.class.getName();
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			Integer number = (Integer)pm.newQuery(query).execute();
			return number.intValue();
		}
		finally {
			pm.close();
		}
	}
}
